package mint;


import java.io.InputStream;
import java.util.Formatter;

import mint.modules.AssemblyCodeGenerator;
import mint.modules.LexicalAnalizer;
import mint.modules.SemanticAnalizer;
import mint.modules.SyntaxAnalizer;
import mint.tools.CLI.CLI;

class Main {
	public static void main(String[] args) {
		CLI cli = new CLI();

		try {
			cli.parse(args, new String[0]);

			InputStream inputStream = args.length == 0 ? System .in
					: new java.io.FileInputStream(cli.getInFile());
			String outfileName = cli.getOutFile();
			
			if (outfileName == null)
				outfileName = "a.out";
			
			Formatter output = new Formatter(outfileName);	
			
			if (cli.getTarget() == CLI.SCAN) {
				LexicalAnalizer.lexer(cli, inputStream, output);
			} else if (cli.getTarget() == CLI.PARSE) {
				SyntaxAnalizer.parse(inputStream, output);
			} else if (cli.getTarget() == CLI.SYMTABLE)
			{
				SemanticAnalizer semantic = new SemanticAnalizer(inputStream, output);				
				semantic.printSymbolTable();
			}
			else if (cli.getTarget() == CLI.SEMANTIC)
			{
				SemanticAnalizer semantic = new SemanticAnalizer(inputStream, output);				
				semantic.parse();
			}
			else if (cli.getTarget() == CLI.ASSEMBLY  || cli.getTarget() == CLI.DEFAULT)
			{
				AssemblyCodeGenerator generator = new AssemblyCodeGenerator(inputStream, output);
				generator.generate();
			}
			output.close();
		} catch (Exception e) {
			// print the error:
			System.out.println(cli.getInFile() + " " + e);
			e.printStackTrace();
		}
	}
}
